package com.alameda.common.config.interceptors;

import com.alameda.common.utils.PubUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

import static com.alameda.common.base.constant.ProjectConstant.TRACE_ID;

/**
 * traceId过滤器
 *
 * @author Lv
 * @date 2024/7/8
 */
@Slf4j
@Component
@Order(2)
public class WebTraceIdInterceptor implements HandlerInterceptor {
    /**
     * 拦截前置处理
     *
     * @param request  http请求对象
     * @param response http响应对象
     * @param handler  拦截方法对象
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 客户端传入链路ID 否则后端生成
        String tid = PubUtils.isNotEmpty(request.getHeader(TRACE_ID)) ?
                request.getHeader(TRACE_ID) :
                UUID.randomUUID().toString().replace("-", "");

        MDC.put(TRACE_ID, tid);
        return true;
    }

    /**
     * 拦截后置处理
     *
     * @param request  http请求对象
     * @param response http响应对象
     * @param handler  拦截方法对象
     * @param ex       异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        MDC.remove(TRACE_ID);
    }
}
